import functools

from flask import (
    Blueprint, g, request, session, jsonify
)
from werkzeug.security import check_password_hash, generate_password_hash

from flaskr.db import get_db

bp = Blueprint('auth', __name__, url_prefix='/auth')

def check_param(params, keys):
    for item in params:
        if item not in keys:
            return -1, jsonify({
                'status': -1,
                'msg': f"{item} is lost!"
            })
    return 0, ""

@bp.before_app_request
def load_logged_in_user():
    username = session.get('username')
    if username is None:
        g.user = None
    else:
        g.user = get_db().execute(
            'SELECT * FROM user WHERE username = ?', (username,)
        ).fetchone()

# 登录验证接口
@bp.route('/verify', methods=['POST'])
def verify():
    if g.user is None:
        return jsonify({
            'status': '-1',
            'msg': '用户未登录'
        })
    else:
        return jsonify({
            'status': '0',
            'msg': '登录验证通过'
        })

@bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    res, msg = check_param(['username', 'password'], data.keys())
    if res == -1: return msg
    db = get_db()
    error = None

    # 检查账号是否已存在
    sql = "select * from user where username = ?;"
    if db.execute(sql, (data['username'], )).fetchone():
        error = "账号已存在"

    if error:
        return jsonify({
            'status': -1,
            'msg': error
        })

    # 添加账号    
    sql = "insert into user(username, password) values(?, ?);"
    db.execute(sql, (data['username'], generate_password_hash(data['password'])))
    db.commit()

    return jsonify({
        'status': 0,
        'msg': '注册成功!'
    })

@bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    res, msg = check_param(['username', 'password'], data.keys())
    if res == -1: return msg
    db = get_db()
    error = None

    # 检查账号是否存在
    sql = "select * from user where username = ?;"
    userinfo = db.execute(sql, (data['username'],)).fetchone()
    if not userinfo:
        error = "账号不存在"
        
    # 验证密码
    if not error and not check_password_hash(userinfo['password'], data['password']):
        error = "密码错误"
    
    if error:
        return jsonify({
            'status': -1,
            'msg': error
        })

    session.clear()
    session['username'] = data['username']

    # 获取一下用户信息
    sql = "select * from user where username = ?;"
    db_data = db.execute(sql, (data['username'], )).fetchone()

    return jsonify({
        'status': 0,
        'msg': '登录成功',
        'username': db_data['username'],
        'nickedname': db_data['nickedname'],
        'headpicture': db_data['headpicture']
    })

@bp.route('/logout', methods=['POST'])
def logout():
    session.clear()
    return jsonify({
        'status': 0,
        'msg': '用户已登出'
    })
    